var event = require('../../../../utils/event.js')
import util from '../../../../utils/util2'
import config from '../../../../utils/config2'
var regeneratorRuntime = require('../../../../lib/js/runtime-module.js')

import Serv from './addBankCardSer.js';


Page({

  /**
   * 页面的初始数据
   */
  data: {
    inputDisable: false,
    bankFlag: false,
    curBankItem: {},
    bankIndex: '',
    time: '获取验证码',
    currentTime: 60,
    disabled: false,
    isSendMsg: false,
    bankList: [],
    user_id: '',
    'cvv2': '',
    'valid_thru': '',
    'linked_acctno': '',
    'linked_phone': '',
    'password': {},
    'verify_code': '',
    submitParams: {//提交参数
      'user_id': '',
      'verify_code': ''
    }
  },
  // 点击数据提交
  formSubmit: async function (e) {
    let pages = getCurrentPages();//当前页面
    let prevPage = pages[pages.length - 2];//上一页面

    let { user_id, verify_code, bankList, bankIndex } = this.data
    let params = {//提交参数
      'user_id': user_id,
      'verify_code': verify_code
    }
    if (params.verify_code === '') {
      wx.showToast({
        title: '请输入验证码',
        icon: 'none',
      })
    }
    let { data, msg, success } =await Serv.bindcardVerify(params)
    if (!success) {
      wx.showToast({
        title: msg || '',
        icon: 'none',
      })
      return false
    }
    //发红包绑定新银卡行
    prevPage.getWalletUser();
    wx.navigateBack({
      delta: 1
  });
  },
  //获取短信验证码
  getCode: async function (options) {
    let that = this;
    let currentTime = that.data.currentTime;
    let { user_id, linked_acctno, linked_phone, password, random_key, bankList, bankIndex, verify_code ,curBankItem} = this.data
    let params = {//验证码参数 user_id  linked_acctno  linked_phone  cvv2  valid_thru  password  random_key
      cvv2: '',
      valid_thru: '',
      user_id: user_id,
      linked_acctno: linked_acctno || '',
      linked_phone: linked_phone || '',
      password: password.pwdMw || '',
      random_key: password.randomKey || '',
      bank_code:curBankItem.bank_code||'',
    };
    // 校验表单
    let regMag = {
      mobile: /^1[345789]\d{9}$/,//手机
      idcard: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,//身份证
      num: /^\d*\.?\d+$/,//数字，可包含小数点
      bankcard: /^\d{6,19}$/g,//银行卡号
    }
    let errormsg = ''
    if (bankIndex === '') {
      errormsg = '请选择开户银行'
    }
    else if (params.linked_acctno == '') {
      errormsg = '请输入银行卡号'
    }
    else if (!regMag.bankcard.test(linked_acctno)) {
      errormsg = '请输入正确的银行卡号'
    }
    else if (params.linked_phone == '') {
      errormsg = '请输入手机号'
    }
    else if (!regMag.mobile.test(linked_phone)) {
      errormsg = '请输入正确的手机号'
    }
    else if (params.password == '') {
      errormsg = '请输入交易密码'
    }
    if (errormsg) {
      wx.showToast({
        title: errormsg || '',
        icon: 'none',
      })
      return false
    }

    // 倒计时
    that.setData({
      time: '重新获取(' + currentTime + 's)',
      disabled: true
    })
    clearInterval(interval)
    var interval = setInterval(function () {
      that.setData({
        time: '重新获取(' + (currentTime - 1) +
          's)'
      })
      currentTime--;
      if (currentTime <= 0) {
        clearInterval(interval)
        that.setData({
          time: '重新获取',
          currentTime: 60,
          disabled: false
        })
      }
    }, 1000)

    // 发起获取验证码请求
    let { success, msg, data = {}, } = await Serv.bindcardApply(params)
    if (!success) {
      wx.showToast({
        title: msg || '',
        icon: 'none',
      })
      clearInterval(interval)
      this.setData({
        time: '获取验证码',
        currentTime: 60,
        disabled: false,
        isSendMsg: false,
      })
      return false
    }
    this.setData({ isSendMsg: true })
  },

  // 获取银行卡列表
  banklist: async function (user_id) {
    //发起请求
    let params = { 'product_type': '1', 'pay_chnl': "10" }
    let { success, msg, data = {}, } = await Serv.banklist(params)
    if (!success) {
      wx.showToast({
        title: msg || '',
        icon: 'none',
      })
      return false
    }
    let bankList= data.support_banklist || [];
    bankList.map((item,index)=>{
      item.logourl=`${config.ossHost}images/logo/${item.bank_code}.png`
      
    })
    this.setData({
      bankList: bankList || [],
    })
  },

  // 表单输入
  bindinput: function (e) {
    let { formData } = this.data
    console.log('bindinput', e.currentTarget.dataset, e.detail)
    let label = e.currentTarget.dataset.label
    let value = e.detail.value
    this.setData({
      [label]: value
    })
  },
  pwdFocus: function (e) {
    let label = e.currentTarget.dataset.label
    // from：当前地址， eventName: 监听定义的事件名
    util.navigateStateChange(this, 'inputDisable');
    wx.navigateTo({
      url: '../../pwdCtrl/pwdCtrl?from=/addBankCard/addBankCard&eventName=onPwdChange' + `&label=${label}`
    })
  },
  //密码控件回调
  pwdCtrlCallback: function () {

  },
  //选择银行弹窗显示隐藏
  toggleShowBank: function () {
    this.setData({bankFlag:!this.data.bankFlag})
  },
  // 选择银行
  selectBank (e) {
    console.log(e.currentTarget.dataset.index)
    let {bankList = [], bankFlag} = this.data
    let {index} = e.currentTarget.dataset
    this.setData({
      bankIndex: index,
      curBankItem: bankList[index]||{},
      bankFlag: !bankFlag
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let { formData } = this.data
    let user_id = wx.getStorageSync(config.userIdKey)
    // console.log('onLoad user_id',user_id)
    this.setData({ user_id })
    this.banklist()
  
    //监听密码控件输入
    var that = this
    event.on('onPwdChange', that, function (changedData) {
      let {pwdMw = '', label = '', randomKey = '',pwdHash='',pwdlen=0} = changedData
      console.log('DataChanged trigger...', changedData, {
        [label]: pwdMw
      })
      that.setData({
        [label]: {
          pwdMw: pwdMw,
          randomKey: randomKey,
          pwdHash: pwdHash,
          pwdlen: pwdlen,
          pwdMw_new: pwdMw.substr(0,pwdlen),
        },
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let that = this
    //取消监听
    event.remove('onPwdChange', that)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {
  //
  // }
})
